package com.zhitong.money.controller;

import com.github.pagehelper.PageInfo;
import com.wf.captcha.SpecCaptcha;
import com.wf.captcha.base.Captcha;
import com.zhitong.money.entity.AjaxResponse;
import com.zhitong.money.entity.TokenEntity;
import com.zhitong.money.entity.User;
import com.zhitong.money.exception.RepeatException;
import com.zhitong.money.mapper.UserMapper;
import com.zhitong.money.services.api.ITokenEntityService;
import com.zhitong.money.services.api.IUserService;
import com.zhitong.money.util.MD5Util;
import com.zhitong.money.util.TokenUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationException;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.ClassUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.thymeleaf.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.*;
import java.util.concurrent.TimeUnit;

@CrossOrigin
@Slf4j
@RestController
public class userContro {

    @Autowired
    private IUserService userService;

    @Autowired
    private ITokenEntityService tokenEntityService;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    /**
     * 登录用户
     * @param user
     * @return
     */
    @PostMapping("/login")
    public AjaxResponse login(@RequestBody Map<String,Object> map) throws Exception{
        String userName=map.get("userName").toString();
        String password=map.get("password").toString();
        String key = map.get("key").toString();
        String verCode = map.get("verCode").toString().toUpperCase().trim();
        String s = null;
        try {
            s = redisTemplate.opsForValue().get(key).trim();
        } catch (Exception e) {
            return AjaxResponse.fail("验证码失效");
        }
        log.info("dfd"+verCode.equals(s));
        if (!verCode.equals(s)){
            return AjaxResponse.fail("验证码错误!");
        }
        User userByUserName = userService.findUserByUserName(userName);
        if (userByUserName==null){
            return AjaxResponse.fail("用户不存在!");
        }
        if (userByUserName.getStatus().equals("00")){
            return AjaxResponse.fail("用户已被冻结!");
        }
        if (!userByUserName.getPassword().equals(MD5Util.encryptPassword(userName,password))){
            return AjaxResponse.fail("密码错误!");
        }else{
            AjaxResponse success = AjaxResponse.success("登录成功!");
            success.setData(tokenEntityService.createToken(userByUserName.getTid()));
            return success;
        }
    }



    @GetMapping("/logout/{id}")
    public AjaxResponse logout(@PathVariable String id, HttpServletRequest request) throws Exception{
        String token = TokenUtil.getToken(request);
        tokenEntityService.logout(token);
        Map<String,Object> map=new HashMap<>();
        map.put("lastTime",new Date());
        map.put("id",id);
        userService.updateLastTime(map);
        return AjaxResponse.success("退出成功!");
    }

    @GetMapping("/captcha")
    public AjaxResponse captcha(HttpServletRequest request, HttpServletResponse response){
        SpecCaptcha specCaptcha = new SpecCaptcha(130, 48, 5);
        specCaptcha.setCharType(Captcha.TYPE_NUM_AND_UPPER);
        String verCode = specCaptcha.text().toUpperCase();
        String verKey = UUID.randomUUID().toString().replace("-","");
        redisTemplate.opsForValue().set(verKey,verCode,60, TimeUnit.SECONDS);
        AjaxResponse success = AjaxResponse.success();
        success.setData(specCaptcha.toBase64());
        success.setMessage(verKey);
        return success;
    }

    
    @GetMapping("/user/{id}")
    public AjaxResponse getUserById(@PathVariable String id) throws Exception{
            User userById = userService.findUserById(id);
            return AjaxResponse.success(userById);
    }

    @GetMapping("/userTid/{tid}")
    public AjaxResponse getUserByTid(@PathVariable String tid) throws Exception{
        User userById = userService.findUserByTid(tid);
        return AjaxResponse.success(userById);
    }



    @GetMapping("/users")
    public AjaxResponse getAllUser() throws Exception{
            List<User> allUser = userService.findAllUser();
            return AjaxResponse.success(allUser);
    }

    @PostMapping("/users")
    public AjaxResponse getUserByPage(@RequestBody Map<String,Object> map) throws Exception{
            PageInfo pageInfo = userService.findUserByPage(map);
            return AjaxResponse.success(pageInfo);
    }

    /**
     *@Author: AndyZhang
     *@Description 校验密码
     *@param map
     *@return
     *@Date: 15:36 2021/2/2
     */
    @PostMapping("/checkPWD")
    public AjaxResponse checkPWDById(@RequestBody Map<String,String> map) throws Exception{
        User user = userService.findUserById(map.get("id"));
        if (MD5Util.encryptPassword(user.getUserName(),map.get("pwd")).equals(user.getPassword())){
            return AjaxResponse.success();
        }else{
            return AjaxResponse.fail("密码不正确");
        }

    }


    /**
     * 添加用户
     * @param map
     * @return
     */
    @RequiresPermissions({"addUser"})
    @PostMapping("/user")
    public AjaxResponse addUser(@RequestBody Map<String,Object> map) throws Exception{
        userService.addUser(map);
        return AjaxResponse.success("添加用户成功");
    }

    /**
     * 更新用户
     * @param map
     * @return
     */
    @RequiresPermissions({"updateUser"})
    @PutMapping("/user")
    public AjaxResponse update(@RequestBody Map<String,Object> map) throws Exception{
        userService.updateUser(map);
        return AjaxResponse.success("修改用户号成功!");
    }

    /**
     * 删除用户
     * @param id
     * @return
     */
    @RequiresPermissions({"delUser"})
    @DeleteMapping("/user/{id}")
    public AjaxResponse delUser(@PathVariable String id) throws Exception{
        userService.delUser(id);
        return AjaxResponse.success("删除用户成功");
    }

    @RequiresPermissions({"delUser"})
    @PostMapping("/delUsers")
    public AjaxResponse delUserByIds(@RequestBody Map<String,Object> map) throws Exception{
        List<String> ids=(List<String>) map.get("delList");
        if (ids==null || ids.isEmpty()){
            return AjaxResponse.fail("请选择职位");
        }
        userService.delUserByIds(map);
        return AjaxResponse.success("删除成功!");
    }


    /**
     *@Author: AndyZhang
     *@Description 头像上传
     *@param file
     *@return
     *@Date: 15:35 2021/2/2
     */
    @PostMapping("/icon")
    public AjaxResponse uploadIcon(@RequestBody MultipartFile file) throws Exception{
        if (file.isEmpty()){
            return null;
        }
        String originName=file.getOriginalFilename();
        String suffixName = originName.substring(originName.lastIndexOf("."));  // 后缀名
        String filePath = ClassUtils.getDefaultClassLoader().getResource("").getPath()+"static/icons"; // 上传后的路径
        String fileName= UUID.randomUUID().toString().replaceAll("-","")+suffixName;
        File file1=new File(filePath,fileName);
        if (!file1.getParentFile().exists()){
            file1.getParentFile().mkdirs();
        }
        try {
            file.transferTo(file1);
            String url="http://127.0.0.1:8090/icons/"+fileName;
            return AjaxResponse.success(url);
        } catch (IOException e) {
            e.printStackTrace();
            throw e;
        }

    }

}
